package com.sunwayhorizo.health.platform.security.service.role;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.Stateless;

import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.business.dto.ResultsDTO;
import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.platform.base.BaseManager;
import com.sunwayhorizo.health.platform.common.PlatformConstant;
import com.sunwayhorizo.health.platform.security.dao.SecurityAccountRoleDao;
import com.sunwayhorizo.health.platform.security.dao.SecurityPermissionDao;
import com.sunwayhorizo.health.platform.security.dao.SecurityPermissionRoleDao;
import com.sunwayhorizo.health.platform.security.dao.SecurityRoleDao;
import com.sunwayhorizo.health.platform.security.persistent.SecurityAccount;
import com.sunwayhorizo.health.platform.security.persistent.SecurityAccountRole;
import com.sunwayhorizo.health.platform.security.persistent.SecurityPermissionRole;
import com.sunwayhorizo.health.platform.security.persistent.SecurityRole;

@Name("SecurityRoleManager")
@Stateless
public class SecurityRoleManager extends BaseManager implements SecurityRoleManagerLocal{

	public ResultsDTO newSecurityRole(SecurityRole role) {
		SecurityRoleDao roleDao = (SecurityRoleDao)Component.getInstance("SecurityRoleDao");
		role = roleDao.newSecurityRole(role);
		return super.getResultsDTO("角色新增成功",true, role.getRoleId());
	}

	public ResultsDTO delSecurityRole(List<String> list) {
		SecurityRoleDao roleDao = (SecurityRoleDao)Component.getInstance("SecurityRoleDao");
		roleDao.deleteSecurityRole(list);
		return super.getResultsDTO("删除角色列表成功",true, null);
	}

	public ResultsDTO updateSecurityRole(SecurityRole role) {
		SecurityPermissionRoleDao permissionRoleDao = (SecurityPermissionRoleDao)Component.getInstance("SecurityPermissionRoleDao");
		SecurityAccountRoleDao accountRoleDao = (SecurityAccountRoleDao)Component.getInstance("SecurityAccountRoleDao");
		permissionRoleDao.deleteSecurityPermissionByRoleId(role.getRoleId());
		accountRoleDao.deleteSecurityAccountByRoleId(role.getRoleId());
		
		if( role.getPermissionRoles()!=null ){
            for( SecurityPermissionRole p: role.getPermissionRoles()){
                p.setPermissionRoleId(null);
            }
        }
		if( role.getAccountRoles() !=null ){
		    for( SecurityAccountRole ar: role.getAccountRoles()){
                ar.setAccountRoleId(null);
            }
		}
		SecurityRoleDao roleDao = (SecurityRoleDao)Component.getInstance("SecurityRoleDao");
		roleDao.updateSecurityRole(role);
		return super.getResultsDTO("角色修改成功",true, null);
	}

	public ResultsDTO findSecurityRoleList() {
		List<SecurityRole> list = ((SecurityRoleDao)Component.getInstance("SecurityRoleDao")).findSecurityRoleList();
		return super.getResultsDTO("查询角色列表成功",true, list);
	}
	
	public ResultsDTO findSecurityRoleListWithOutRootNode() {
        List<SecurityRole> list = ((SecurityRoleDao)Component.getInstance("SecurityRoleDao")).findSecurityRoleListWithOutRootNode();
        return super.getResultsDTO("查询根节点之外的角色列表成功",true, list);
    }

	public ResultsDTO findSecurityRoleDetailById(String roleId) {
		SecurityRoleDao roleDao = (SecurityRoleDao)Component.getInstance("SecurityRoleDao");
		SecurityRole role = roleDao.findSecurityRoleDetailById(roleId);
		return super.getResultsDTO("查询角色详细信息成功",true, role);
	}

	public ResultsDTO findSecurityRoleTree() {
		List<SecurityRole> result = new ArrayList<SecurityRole>();
		List<SecurityRole> list = ((SecurityRoleDao)Component.getInstance("SecurityRoleDao")).findSecurityRoleListWithFatherRole();
		for( int i=0;ListUtil.isNotEmpty(list)&&i<list.size();i++){
		    super.entityManager2.refresh(list.get(i));
		    
		    List<SecurityAccountRole> accountRoleList = list.get(i).getAccountRoles();
		    for( int j=0;ListUtil.isNotEmpty(accountRoleList)&&j<accountRoleList.size();j++){
		        SecurityAccount sa = accountRoleList.get(j).getAccount();
		        if( sa!=null && "1".equals(sa.getDeleted()) ){
		            //去除逻辑删除的账号 findSecurityRoleListWithFatherRole这个里面关联不起作用，层次太深
		            accountRoleList.remove(accountRoleList.get(j));
		        }
		    }
		    
		}
		result.add(init(list));
		super.entityManager2.clear();
		return super.getResultsDTO("查询角色列表成功",true, result);
	}

	@Override
	public ResultsDTO findSecurityRoleListByAccountIdWithScreen(String accountId){
		SecurityRoleDao roleDao = (SecurityRoleDao)Component.getInstance("SecurityRoleDao");
		return super.getResultsDTO("通过账号查询角色列表成功",true, roleDao.findSecurityRoleListByAccountIdWithScreen(accountId));
	}
	
	@Override
	public ResultsDTO findSecurityRoleListByAccountIdWithOutScreen(String accountId) {
		SecurityRoleDao roleDao = (SecurityRoleDao)Component.getInstance("SecurityRoleDao");
		return super.getResultsDTO("通过账号查询角色列表成功",true, roleDao.findSecurityRoleListByAccountIdWithOutScreen(accountId));
	}
	
	@Override
	public ResultsDTO findSecurityPermissionListByRoleId(String roleId) {
		SecurityPermissionDao permissionDao = (SecurityPermissionDao)Component.getInstance("SecurityPermissionDao");
		return super.getResultsDTO("通过角色查询权限列表（无树型结构）成功",true, permissionDao.findSecurityPermissionListByRoleId(roleId));
	}
	
	public ResultsDTO validateUniqueSecurityRole(String roleId, String roleName) {
		SecurityRoleDao roleDao = (SecurityRoleDao)Component.getInstance("SecurityRoleDao");
		try{
			SecurityRole dbRoleByName = roleDao.findSecurityRoleDetailByName(roleName);
			if(StrUtil.isEmpty(roleId)){
				return super.getResultsDTO("角色名称已经存在",false, null);
			}else{
				if( roleId.equals(dbRoleByName.getRoleId())){
					return super.getResultsDTO("角色名称可以使用",true, null);
				}else{
					return super.getResultsDTO("角色名称已经存在",false, null);
				}
			}
		}catch(Exception e){
			return super.getResultsDTO("角色名称可以使用",true, null);
		}
	}
	
	private SecurityRole init( List<SecurityRole> list ){
		Map<String,SecurityRole> map = new LinkedHashMap<String,SecurityRole>();
		for( SecurityRole r:list){
			map.put(r.getRoleId(), r);
		}
		return initTree(map);
	}
	
	private SecurityRole initTree( Map<String,SecurityRole> treeRole){
		for( String key: treeRole.keySet() ){
			SecurityRole sub = treeRole.get(key);
			SecurityRole father = sub.getFatherRole();
			if( father != null ){
				father.addChild(sub);
				treeRole.put(father.getRoleId(), father);
			}
		}
		return treeRole.get(PlatformConstant.ROOT_ROLE);
	}
}